<?php
namespace yan\ip;

class Ipv4{
    /**
     * 判断子网掩码
     * */
    public static function subnetMask($input){
        $subnet_mask = false;
        if(is_int($input)){
            $subnet_mask = long2ip(ip2long("255.255.255.255") << (32 - $input));
        }else{
            $data = self::isCIDRMask($input);
            if($data!==false){
                $subnet_mask = long2ip(ip2long("255.255.255.255") << (32 - $data['1']));
            }else if(self::isSubnetMask($input)){
                $subnet_mask = $input;
            }
        }
        return $subnet_mask;
    }
    /***
     * IP 网段
     * */
	public static function segment($ip, $base=24){
        $subnet_mask = long2ip(ip2long("255.255.255.255") << (32 - $base));
        $ipLong = ip2long($ip);
        $maskLong = ip2long($subnet_mask);

        // 计算网络地址
        $networkAddress = $ipLong & $maskLong;
        // 计算网络地址的反码（即补码）
        // $networkAddressComplement = ~$networkAddress;
        return long2ip($networkAddress);
    }
    /**
     * param ip = 192.168.1.1/24
     * param ip2 = 192.168.1.1 or 192.168.1.1/24
     * */
    public static function isSameSubnet($ip, $ip2){
        $arr = explode('/', $ip);
        $arr2 = explode('/', $ip2);

        $netbits = isset($arr['1']) ? intval($arr['1']) : null;
        $netbits2 = isset($arr2['1']) ? intval($arr2['1']) : null;
        if($netbits===null && $netbits2===null){
            return $ip== $ip2;
        }
        $netbits = $netbits===null ? $netbits2 : $netbits;
        $netbits2 = $netbits2===null ? $netbits : $netbits2;
        $net_addr = self::segment($arr['0'], $netbits);
        $net_addr2 = self::segment($arr2['0'], $netbits2);
        return $net_addr == $net_addr2;
    }
    /**
     * 192.168.1.0/24
     * */
    public static function isCIDRMask($cidr) {
        if (preg_match('/^(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/', $cidr)) {
            list($ip, $prefix) = explode('/', $cidr);
            if ($prefix >= 0 && $prefix <= 32) {
                return [$ip, $prefix];
            }
        }
        return false;
    }
    /**
     * 255.255.255.0
     * */
    public static function isSubnetMask($ip) {
        // 将IP地址转换为长整型
        $ipLong = ip2long($ip);
        $ip2_string = decbin($ipLong);
        preg_match('/^1+/', $ip2_string, $matches);
        $len = 0;
        if($matches){
            $len = strlen($matches['0']);
        }
        if($len===0 || $len > 32){
            return false;
        }
        // echo decbin($ipLong) . "<br/>";
        // echo decbin(($ipLong << $len)) . "<br/>";
        $mask = $ipLong << $len & 0xffffffff;
        // echo decbin($mask) . "<br/>";
        // var_dump($mask);
        return $mask===0;
        // 检查是否为连续的1（子网掩码的最后几位）
        // $mask = -1 & $ipLong;  // 生成连续的1
        // return ($ipLong & $mask) == $ipLong;
    }
}